﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Net.Mail;
using Microsoft.SqlServer.Server;
using System.Threading;
using System.Globalization;
using Nivdal.AuxCode;
using System.Web.Script.Services;
//using System.Diagnostics;


namespace Nivdal
{
    public partial class BigMasterPage : System.Web.UI.MasterPage
    {
        public string version { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            // Remove this for production:
            //if (!(bool)Session["shmdb"]) Response.Redirect("~/Default.aspx");

            try
            {
                version = ConfigurationManager.AppSettings["version"];
            }
            catch
            {
                version = "999.0.0.0";
            }
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            
            // load css and js:
            stylesheetNewCssLiteral.Text = "<link href=\"stylesheetNew.css?v=" + version + "\" rel=\"stylesheet\" type=\"text/css\" />";
            NoamStylesLiteral.Text = "<link href=\"NoamStyles/Global.css?v=" + version + "\" rel=\"stylesheet\" type=\"text/css\" />";
            ChatJSLiteral.Text = "<script src=\"JS/ChatJScript_111.js?v=" + version + "\" type=\"text/javascript\"></script>";

            if (Request.UserAgent.IndexOf("AppleWebKit") > 0)
            {
                Request.Browser.Adapters.Clear();
            }
            if (!IsPostBack)
            {
                //Session["PrevPage"] = null;
                //Debug.WriteLine("HttpContext.Current " + HttpContext.Current);
                if ((HttpContext.Current != null) && (ou.UserId != null))
                {
                   string current_url = HttpContext.Current.Request.Url.ToString();
                   // Debug.WriteLine("current page " + current_url);
                    string  prev_url = Request.ServerVariables["HTTP_REFERER"];
                    //Debug.WriteLine("prev page " + prev_url);
                    if (prev_url != null && prev_url.Length > 0)
                        GND.ExecNivdalSQL("PageName", "Entry", "NewbieTipStage", "UserId", "Nivdal_AddPageStatistic", prev_url, false, Session["NewbieTipStage"], ou.UserId);
                    if (current_url != null && current_url.Length > 0)
                        GND.ExecNivdalSQL("PageName", "Entry", "NewbieTipStage", "UserId", "Nivdal_AddPageStatistic", current_url, true, Session["NewbieTipStage"], ou.UserId);
                }
                if (ou.UserId != null)
                {
                    this.Panel1.Visible = true;
                    this.UserID.Value = "1";
                    LoadExistingChats();
                }
                
               // Page.ClientScript.RegisterStartupScript
               //(this.GetType(), "alert", "JS_InitAllChatWindows();", true);
                // masterBody is the ID of the masterpage body html tag       
                //HtmlGenericControl body = 
                //(HtmlGenericControl)Page.Master.FindControl("masterBody");
                //body.Attributes.Add("onunload", "Nivdal_OpenNewChatRoom(string FriendId);");
                DateTime ServerTime = System.DateTime.Now;
                SqlConnection myConnection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                SqlCommand storedProcCommand = new SqlCommand("Nivdal_Date", myConnection);
                storedProcCommand.CommandType = CommandType.StoredProcedure;
                SqlDataReader myReader;
                try
                {
                    myConnection.Open();
                    myReader = storedProcCommand.ExecuteReader();
                    while (myReader.Read())
                        ServerTime = ((DateTime)myReader.GetSqlDateTime(0));
                    // always call Close when done reading.
                    myReader.Close();

                }
                catch (Exception SQLDBException)
                {

                    Response.Write(Convert.ToString(SQLDBException));

                }

                finally
                {
                    // Close the connection when done with it.
                    myConnection.Close();

                }
                //Response.Write(ServerTime.ToString());
                const string crlf = "\r\n";
                string js = "<script type='text/javascript'>" + crlf +
                "window.onload=startclock;" + crlf +
                "var clock;" + crlf +
                "var time_diff;" + crlf +
                "function startclock(){" + crlf +
                   "clock=document.getElementById('clock');" + crlf +
                   "server_time = new Date('" + ServerTime.ToString(CultureInfo.CreateSpecificCulture("en-us")) + "');"
                   + crlf +
                   "time_diff=new Date()-server_time;" + crlf +
                   "setInterval('runclock()',1000);" + crlf +
                "}" + crlf +
                "function runclock(){" + crlf +
                   "var cDate=new Date();" + crlf +
                   "cDate.setTime(cDate.getTime()-time_diff);" + crlf +
                   "var curr_year = cDate.getFullYear();" + crlf +
                   "var curr_month = cDate.getMonth()+1;" + crlf +
                   "var curr_day = cDate.getDate();" + crlf +
                   "var curr_hours = cDate.getHours();" + crlf +
                   "var curr_mins = cDate.getMinutes();" + crlf +
                   "var curr_secs = cDate.getSeconds();" + crlf +
                   "curr_hours=(curr_hours < 10)?'0' + curr_hours:curr_hours;" + crlf +
                   "curr_mins=(curr_mins < 10)?'0' + curr_mins:curr_mins;" + crlf +
                   "curr_secs=(curr_secs < 10)?'0' + curr_secs:curr_secs;" + crlf +
                   "clock.innerHTML=curr_month+'-'+curr_day+'-'+curr_year+'  '+curr_hours+':'+curr_mins+':'+curr_secs;" + crlf +
                   "}" + crlf +
                "</script>";

                //Page.RegisterStartupScript("js", js);
                Page.ClientScript.RegisterStartupScript(this.GetType(), "js", js);

                // TODO: This is to enable adds for premium only. Removed for a while.
                //AddsPanel.Visible = ((!ou.IsPremium) || (ou.UserAccessLevel == "5"));
                

                //TopInvitationPanel.Visible = true;  ///(ou.IsPremium);

                // this part will be a bit too heavy:
                //this.NumberOfOnlineUsersLabel.Text = (GND.ReadNivdalIntData("Nivdal_GetNumberOfOnlineUsers")).ToString();


                // return this once the number of online users will be higher (for some reason the number of online users
                // that is shown this way is sometimes getting x20 too high. So when the number of users is not that big - it is strange.
                //this.NumberOfOnlineUsersLabel.Text = Application["ActiveUsers"].ToString();
                //this.NumberOfActiveUsersLabel.Text = NumOfActiveUsers().ToString();

                //string TopAreaImageUrl = GND.ReadNivdalStringData("UserId", "Nivdal_GetTopAreaImage", ou.UserId);
                
                //if (ou.TopAreaImage == "null")
                //    TopAreaImage.Visible = false;
                //else
                //{
                //    TopAreaImage.ImageUrl = "~/Images/TopAreaImages/" + ou.TopAreaImage;
                //}

            
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {

                    // set language:
                    DropDownList Lang_ddl = (LoginView2.FindControl("PreferredLanguageDropDownList") as DropDownList);
                    Lang_ddl.SelectedValue = ou.Language;

                    

                    // add user id to be MessagesDataSourse parameter:
                    this.MessagesDataSourse.SelectParameters.Clear();
                    this.MessagesDataSourse.SelectParameters.Add("UserId", ou.UserId);
                    this.NewsDataSourse.SelectParameters.Clear();
                    this.NewsDataSourse.SelectParameters.Add("UserId", ou.UserId);
                    this.LiveDataSource.SelectParameters.Clear();
                    this.LiveDataSource.SelectParameters.Add("UserId", ou.UserId);
                    this.FriendsOnlineDataSourse.SelectParameters.Add("UserId", ou.UserId);
                
                    switch (ou.TextDir)
                    {
                        case "LeftToRight":
                            DirectionPanel.Direction = ContentDirection.LeftToRight;
                            //ServerClockPanel.Direction = ContentDirection.LeftToRight;
                            StyleSheetLiteral.Text = "<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheetLTR.css?v=" + version + "\" />";
                            break;
                        case "RightToLeft":
                            DirectionPanel.Direction = ContentDirection.RightToLeft;
                            //ServerClockPanel.Direction = ContentDirection.RightToLeft;
                            StyleSheetLiteral.Text = "<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheetRTL.css?v=" + version + "\" />";
                            break;
                        default:
                            DirectionPanel.Direction = ContentDirection.LeftToRight;
                            //ServerClockPanel.Direction = ContentDirection.LeftToRight;
                            StyleSheetLiteral.Text = "<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheetLTR.css?v=" + version + "\" />";
                            break;
                    }


                    //Repeater Live = (LoginView1.FindControl("LiveListView") as Repeater);
                    UpdatePanel Live = (LoginView1.FindControl("LiveUpdatePanel") as UpdatePanel);
                    if (HttpContext.Current.User.Identity.IsAuthenticated && GND.ReadNivdalBoolData("UserId", "Nivdal_DoesUserHaveGamesInLive", ou.UserId))
                    {
                        Live.Visible = true;
                        
                    }
                    else
                    {
                        Live.Visible = false;
                    }

                }
                else
                {
                    CultureInfo Cult = ResolveCulture();
                    if ((Cult != null) && (Cult.TextInfo.IsRightToLeft))
                    {
                        try
                        {
                            StyleSheetLiteral.Text = "<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheetRTL.css\" /><link type=\"text/css\" rel=\"stylesheet\" href=\"NoamStyles/Default.css\" />";
                            (LoginView1.FindControl("LoginPanel") as Panel).Direction = ContentDirection.RightToLeft;
                            DirectionPanel.Direction = ContentDirection.RightToLeft;
                            
                        }
                        catch { }
                    }
                    else 
                    {
                        try
                        {
                            StyleSheetLiteral.Text = "<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheetLTR.css\" /><link type=\"text/css\" rel=\"stylesheet\" href=\"NoamStyles/Default.css\""; 
                            (LoginView1.FindControl("LoginPanel") as Panel).Direction = ContentDirection.LeftToRight;
                            DirectionPanel.Direction = ContentDirection.LeftToRight;                            
                        }
                        catch { }
                    }


                }

                FriendsOnlineUpdatePanel.Visible = (ou.IsPremium && HttpContext.Current.User.Identity.IsAuthenticated);
            }
        }


        protected void Page_Unload(object sender, EventArgs e)
        {
            //if (!IsPostBack)
            //{
                //if (Request.ServerVariables["HTTP_REFERER"] != null)
                //{

                //    Debug.WriteLine("prev page " + Request.ServerVariables["HTTP_REFERER"]);
                //}
           // }

        }
      

        public static CultureInfo ResolveCulture()
        {
            string[] languages = HttpContext.Current.Request.UserLanguages;
            if (languages == null || languages.Length == 0)
                return null;
            try
            {
                string language = languages[0].ToLowerInvariant().Trim();
                return System.Globalization.CultureInfo.CreateSpecificCulture(language);
            }
            catch (ArgumentException)
            {
                return null;
            }
        }

        protected int NumOfActiveUsers()
        {

            string conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            System.Data.SqlClient.SqlConnection
            strConnection = new System.Data.SqlClient.SqlConnection(conn);
            string StrSQL = "Nivdal_GetNumberOfActiveUsers";
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(StrSQL, strConnection);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ROWCOUNT", System.Data.SqlDbType.Int, 0));
            cmd.Parameters["@ROWCOUNT"].Direction = ParameterDirection.ReturnValue;

            strConnection.Open();
            try
            {

                cmd.ExecuteNonQuery();
                return (int)(cmd.Parameters["@ROWCOUNT"].Value);

            }
            catch (Exception SQLDBException)
            {
                Response.Write(SQLDBException.Message);
                //Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "<script type=\"text/javascript\">alert('" + SQLDBException.Message + "');</script>");
                return 0;

            }

            finally
            {

                strConnection.Close();
            }

        }

        protected void MasterTimerTick(object sender, EventArgs e)
        {
            try
            {

                FormView MessagesFormView = (FormView)LoginView1.FindControl("MessagesFormView");
                ListView NewsListView = (ListView)LoginView1.FindControl("NewsListView");
                MessagesFormView.DataBind();
                NewsListView.DataBind();
                ///this.MessagesFormView.DataBind();
                //this.NewsListView.DataBind();
            }
            catch { }
            finally { }

        }

        protected void LiveRefresh(object sender, EventArgs e)
        {
            //ListView 
            (LoginView1.FindControl("LiveListView") as Repeater).DataBind();

            ///LiveListView.DataBind();
        }

        protected string ParseMoney(object str)
        {
            string ReturnValue;
            int Ammount;
            try
            {
                if (int.TryParse(str.ToString(), out Ammount))
                {
                    ReturnValue = Ammount.ToString("N0");
                    if (Ammount < 0)
                        ReturnValue = "<span class=\"red_inline_text\">" + ReturnValue + "</span>";
                }
                else
                    ReturnValue = "";
                
            }
            catch
            {
                ReturnValue = "";
            }
            return ReturnValue;
        }

        protected System.Drawing.Color ReturnBalanceColor(Object Balance)
        {
            try
            {
                string CurrentBalance = Balance.ToString();
                int numVal = Convert.ToInt32(CurrentBalance);
                if (numVal < 0)
                    return System.Drawing.Color.Red;
                else
                    return System.Drawing.Color.Green;
            }
            catch { return System.Drawing.Color.Green; }

        }

        protected void LoadExistingChats()
        {
            int index = 1;
            string ChatRoomId = null;
            HiddenField ChatIdHiddenField = null;
            HiddenField LastMessageIdHiddenField;
            HyperLink FriendNameHyperlink = null;
            //Image OnlineImg = null;
            //Image OfflineImg = null;
            Label MessagesLabel = null;

            OnlineUser ou = (OnlineUser)Session["User"];
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            SqlCommand cmd = new SqlCommand("Nivdal_GetUserChats", conn);
            SqlDataReader reader;
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@UserId", ou.UserId));
            try
            {
                conn.Open();
                reader = cmd.ExecuteReader();
                if (reader.HasRows)
                    while (reader.Read())
                    {
                        //ChatIdHiddenField = "ChatIdHiddenField" + index.ToString();
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        ChatIdHiddenField = this.FindControl(sb.Append("ChatIdHiddenField" + index.ToString()).ToString()) as HiddenField;
                        ChatRoomId = reader.GetDecimal(0).ToString();
                        ChatIdHiddenField.Value = ChatRoomId;
                        FriendNameHyperlink = this.FindControl("FriendNameHyperlink"  + index.ToString()) as HyperLink;
                        FriendNameHyperlink.NavigateUrl = "UserPage.aspx?Id=" + reader.GetGuid(1).ToString();
                        FriendNameHyperlink.Text = reader.GetString(2);
                        MessagesLabel = this.FindControl("MessagesLabel" + index.ToString()) as Label;
                        MessagesLabel.Text = GetAllChatRoomMessages(ChatRoomId);
                        LastMessageIdHiddenField = this.FindControl("LastMessageHiddenField" + index.ToString()) as HiddenField;
                        LastMessageIdHiddenField.Value = reader.GetDecimal(3).ToString();

                        ////IsOnline – bit that tells whether the friend is online or not
                        //OfflineImg = this.FindControl("IsOfflineImage" + index.ToString()) as Image;
                        //OnlineImg = this.FindControl("IsOnlineImage" + index.ToString()) as Image;
                        //if (reader.GetBoolean(3) == true)
                        //{
                        //    OnlineImg.Visible = true;
                        //    OnlineImg.Visible = false;

                        //}
                        //else
                        //{
                        //    OnlineImg.Visible = false;
                        //    OnlineImg.Visible = true;
                        //}



                            index++;
                    }

            }
            catch (Exception SQLDBException)
            {

                Response.Write(Convert.ToString(SQLDBException));

            }

            finally
            {
                // Close the connection when done with it.
                conn.Close();

            }

        }

        protected string GetAllChatRoomMessages(string ChatroomId)
        {
            int index = 1;
            string RoomMessages = "";
            OnlineUser ou = (OnlineUser)Session["User"];
            string UserName = ou.UserName;
            string CurrnentMessage;
            string CurrentMessageUserName;

            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            SqlCommand cmd = new SqlCommand("Nivdal_GetAllChatRoomMessages", conn);
            SqlDataReader reader;
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add(new SqlParameter("@ChatroomId", ChatroomId));
            cmd.Parameters.Add(new SqlParameter("@UserId", ou.UserId));
            try
            {
                conn.Open();
                reader = cmd.ExecuteReader();
                if (reader.HasRows)
                    while (reader.Read())
                    {
                        if (RoomMessages.Length > 0)
                            RoomMessages += "<br /> "; 
                        CurrnentMessage =  GlobalFunctions.LightEncodeHtmlFromText(reader.GetString(0));
                        CurrentMessageUserName = reader.GetString(1);
                        if (CurrentMessageUserName == UserName)
                        {
                            RoomMessages += "<span style=\"color:Blue; font-weight:bold;\">" + Resources.Resource.Chat_You + ":</span> ";
                        }
                        else
                        {
                            RoomMessages += "<span style=\"color:#658321; font-weight:bold;\">" + GlobalFunctions.LightEncodeHtmlFromText(CurrentMessageUserName) + ":</span> "; 
                        }
                        //RoomMessages = RoomMessages + reader.GetString(2);
                        RoomMessages += CurrnentMessage;
                        index++;
                    }

            }
            catch (Exception SQLDBException)
            {

                Response.Write(Convert.ToString(SQLDBException));

            }

            finally
            {
                // Close the connection when done with it.
                conn.Close();

            }

            return RoomMessages;

        }

        protected bool FriendlyVisible()
        {
            //OnlineUser ou = (OnlineUser)Session["User"];
            //return ou.CanPlayFriendlies && ou.IsPremium;

            // removed - hiding makes it strange for users
            return true;
        }

        protected void FriendsOnlineRefresh(object sender, EventArgs e)
        {
            this.FriendsOnlineListView.DataBind();
        }

        protected string ShortUserName(string Name)
        {
            if (Name.Length <= 8)
                return Name;
            return Name.Substring(0, 7) + "...";
        }

        protected void ChangeLanguage(object Sender, EventArgs e)
        {
            DropDownList Lang_ddl = (LoginView2.FindControl("PreferredLanguageDropDownList") as DropDownList);

            if (Lang_ddl.SelectedValue != "1")
            {
                OnlineUser ou = (OnlineUser)Session["User"];
                GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                ou.Language = Lang_ddl.SelectedValue;
                GND.ExecNivdalSQL("UserId", "Language", "Nivdal_SetUserLaguage", ou.UserId, ou.Language);
                ou.Culture = GND.ReadNivdalStringData("@Language_Code", "Nivdal_GetLanguageCulture", ou.Language);
                ou.UICulture = GND.ReadNivdalStringData("@Language_Code", "Nivdal_GetLanguageUICulture", ou.Language);
                ou.TextDir = GND.ReadNivdalStringData("Language_Code", "Nivdal_GetLanguageTextDirection", ou.Language);
                Response.Redirect(Request.RawUrl);
            }
        }

        protected string numtoshow(object num)
        {
            int result;
            if (int.TryParse(num.ToString(), out result))
                return ((result > 99) ? "99+" : result.ToString());
            return num.ToString();
        }

    }

}

